package com.zx.zxpicture.shared.websocket.disruptor;
import com.zx.zxpicture.domain.user.entity.User;
import com.zx.zxpicture.shared.websocket.model.PictureEditRequestMessage;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;

import javax.annotation.PreDestroy;
import javax.annotation.Resource;

/**
 * disruptor图片编辑事件生产者
 */
@Component
public class PictureEditEventProducer {
    /**
     * disruptor
     */
    @Resource
    private Disruptor<PictureEditEvent> pictureEditEventDisruptor;

    public void publishEvent(PictureEditRequestMessage pictureEditRequestMessage, WebSocketSession session, User user, Long pictureId) {
        //获取环形缓冲区(队列)
        RingBuffer<PictureEditEvent> ringBuffer = pictureEditEventDisruptor.getRingBuffer();
        //获取可以存放任务的位置
        //如果当前位置的消息还没有被处理，则会阻塞等待
        long next = ringBuffer.next();
        //获取这个空事件
        PictureEditEvent pictureEditEvent = ringBuffer.get(next);
        pictureEditEvent.setPictureEditRequestMessage(pictureEditRequestMessage);
        pictureEditEvent.setSession(session);
        pictureEditEvent.setUser(user);
        pictureEditEvent.setPictureId(pictureId);
        //发布事件
        ringBuffer.publish(next);
    }
    /**
     * 优雅停机
     * 等待disruptor队列中所有任务处理完才会关闭
     */
    @PreDestroy
    public void close() {
        pictureEditEventDisruptor.shutdown();
    }
}
